import { getToken, setToken } from '@/utils/auth'
import { sysProfile, sysUser, login } from '@/api/user'
import asyncRouter from '@/router/modules/index'
import router from '@/router'
import { constantRoutes } from '@/router'
import {resetRouter} from '@/router'
const state = {
  token: '' || getToken(),
  userInfo: ''
}
const mutations = {
  setToken(state, value) {
    state.token = value
    setToken(value)
  },
  setUserInfo(state, value) {
    state.userInfo = value
  },
  logout(state) {
    state.token = ''
    setToken('')
    state.userInfo = ''
    //重置路由
    resetRouter()
  }
}
const actions = {
  async isLogin({ commit }, value) {
    const res = await login(value)
    commit('setToken', res.data)
    console.log(res)
  },
  // 获取个人用户信息,
  async getUserInfo({ commit, state }) {
    // 获取员工部分信息,不包含头像
    const res = await sysProfile()
    // 通过userID获取其他信息
    const res2 = await sysUser(res.data.userId)
    // 合并两大对象res,res2
    commit('setUserInfo', { ...res.data, ...res2.data })
    console.log('个人用户信息', res, res2)

    //讲用户信息中的权限数据与动态路由配置匹配，讲匹配项的路由配置添加到路由中
    const newArr = asyncRouter.filter((item) => {
      return state.userInfo.roles.menus.includes(item.children[0].meta.name)
    })
    //因为添加的路由不能立马使用，他会匹配都404，所需要将404匹配路由动态添加
    newArr.push({ path: '*', redirect: '/404', hidden: true })
    console.log('newArr', newArr)
    //将匹配项添加到路由配置中，router.addRoutes（【路由配置】）添加新的路由配置
    commit('routes/setRoutesList', [...constantRoutes, ...newArr], {
      root: true
    })
    // router.addRoutes(newArr)
    router.addRoutes(newArr)
    //addRoutes添加的路由不能立马使用，需要经历一次导航守卫才能正常使用
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
